package commEnv

import (
	"os"
	"strings"
)

type appArgs struct {
	params map[string]interface{}
}

func (e *appArgs) initialize() {
	// os.Args是一个字符串切片，其中第一个元素是程序本身的路径，其余元素是传入的参数
	args := os.Args

	e.params = e.getFoxArgs(args, 0)
}

func (e *appArgs) getFoxArgs(args []string, offset int) map[string]interface{} {
	params := make(map[string]interface{})

	params["appEngine"] = e.getArgs(args, offset, "--app_engine=", "")
	params["appType"] = e.getArgs(args, offset, "--app_type=", "")
	params["appName"] = e.getArgs(args, offset, "--app_name=", "")
	params["appPort"] = e.getArgs(args, offset, "server.port=", "")
	params["envType"] = e.getArgs(args, offset, "--env_type=", "")
	params["envCpuId"] = e.getArgs(args, offset, "--env_cpu_id=", "")
	params["workMode"] = e.getArgs(args, offset, "--work_mode=", "")
	params["envDev"] = e.getArgs(args, offset, "--env_dev=", "")
	params["envDBType"] = e.getArgs(args, offset, "--env_database=", "")

	params["https.certFile"] = e.getArgs(args, offset, "https.certFile=", "")
	params["https.keyFile"] = e.getArgs(args, offset, "https.keyFile=", "")

	params["redis.host"] = e.getArgs(args, offset, "redis.host=", "")
	params["redis.port"] = e.getArgs(args, offset, "redis.port=", "")
	params["redis.password"] = e.getArgs(args, offset, "redis.password=", "")

	params["mysql.host"] = e.getArgs(args, offset, "mysql.host=", "")
	params["mysql.port"] = e.getArgs(args, offset, "mysql.port=", "")
	params["mysql.username"] = e.getArgs(args, offset, "mysql.username=", "")
	params["mysql.password"] = e.getArgs(args, offset, "mysql.password=", "")
	params["mysql.database"] = e.getArgs(args, offset, "mysql.database=", "")

	return params
}

func (e *appArgs) getArgs(args []string, offset int, prefix, defaultValue string) string {
	for i, arg := range args {
		if i < offset {
			continue
		}

		if !strings.HasPrefix(arg, prefix) {
			continue
		}

		return arg[len(prefix):]
	}

	return defaultValue
}
